from django.contrib.auth.hashers import make_password
from django.http import HttpResponse
# render参数是模板，redirect参数是路由
from django.shortcuts import render, redirect
from django.urls import reverse

# 表单类
from .forms import LoginForm, RegisterForm, UpdatePasswordForm, CenterForm
# 用户类
from .models import CustomUser
from django.contrib.auth.views import auth_login, auth_logout, login_required


# Create your views here.
@login_required
def updatepassword(request):
    error = None
    upf = UpdatePasswordForm()
    if request.method == "POST":
        # 重新生成对象，将之前的表单数据保留
        upf = UpdatePasswordForm(data=request.POST)
        password0 = request.POST.get("password0")
        password1 = request.POST.get("password1")
        password2 = request.POST.get("password2")
        if not request.user.check_password(password0):
            error = "原始密码错误"
        else:
            if password1 != password2:
                error = "新密码不一致"
            else:
                # 修改密码
                request.user.set_password(password1)
                # 保存修改
                request.user.save()
                auth_logout(request)
                return redirect(to=reverse("user:login"))
    return render(request, 'user/updatepassword.html', context={"error": error,"upf":upf})


# def login(request):
#     error = None
#     if request.method == "POST":
#         username = request.POST.get("username")
#         password = request.POST.get("password")
#         user = CustomUser.objects.filter(username=username).first()
#         # 用户名是否存在
#         if user:
#             # 检查密码是否正确
#             if user.check_password(password):
#                 # 添加登录的cookie状态
#                 auth_login(request, user)
#                 # 获取get请求中的next部分（下一个路由）
#                 next_url = request.GET.get("next")
#                 if next_url:
#                     # 跳转
#                     return redirect(to=next_url)
#                 else:
#                     # 跳转到首页
#                     return redirect('/')
#             else:
#                 error = "密码错误"
#         else:
#             error = "用户名不存在"
#
#     return render(request, 'user/login.html', context={"error": error})

def login(request):
    # 表单对象lgs
    lgs = LoginForm()
    error = None
    if request.method == "POST":
        # 重新生成对象，将之前的表单数据保留
        lgs = LoginForm(data=request.POST)
        username = request.POST.get("username")
        password = request.POST.get("password")
        # 返回的是一个 QuerySet 对象的第一个
        user = CustomUser.objects.filter(username=username).first()
        # 用户名是否存在
        if user:
            # 检查密码是否正确
            if user.check_password(password):
                # 添加登录的cookie状态
                auth_login(request, user)
                # 获取get请求中的next部分（下一个路由）
                next_url = request.GET.get("next")
                if next_url:
                    # 跳转
                    return redirect(to=next_url)
                else:
                    # 跳转到首页
                    return redirect(to=reverse("main:index"))
            else:
                error = "密码错误"
        else:
            error = "用户名不存在"

    return render(request, 'user/login2.html', context={"error": error, "lgs": lgs})


def logout(request):
    # 清除登录的cookie状态
    auth_logout(request)
    return redirect(to=reverse("main:index"))


def register2(request):
    error = None
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        password2 = request.POST.get("password2")
        if password != password2:
            error = "密码不一致"
        else:
            # 判断输入的用户名是否存在
            if CustomUser.objects.filter(username=username).exists():
                error = "用户名已存在"
            else:
                # 创建用户
                user = CustomUser.objects.create_user(username=username, password=password)
                # 添加登录状态
                auth_login(request, user)
                return redirect(to=reverse("main:index"))
    return render(request, 'user/register.html', context={'error': error})


def register(request):

    rgf = RegisterForm()
    if request.method == "POST":
        # 表单类
        rgf = RegisterForm(request.POST)
        if rgf.is_valid():
            password = rgf.cleaned_data.get("password")
            password2 = rgf.cleaned_data.pop("password2")
            if password != password2:
                rgf.errors.update({
                    "password":["密码不一致"]
                })
                print(rgf.fields,'-----------')
            else:
                user = rgf.save(commit=False)
                # 密码加密
                user.password = make_password(password)
                # 保存
                user = rgf.save()
                # 添加登录状态
                auth_login(request, user)
                return redirect(to=reverse("main:index"))
    return render(request, 'user/register.html', context={'rgf': rgf})


# 通过装饰器确保访问该路由处于登录状态
@login_required
def center(request):
    cf = CenterForm(initial={
        'username': request.user.username,
        'email': request.user.email,
        'telephone': request.user.telephone,
        'first_name': request.user.first_name,
        'last_name': request.user.last_name,
    })

    if request.method == "POST":
        cf = CenterForm(request.POST, files=request.FILES, instance=request.user)
        if cf.is_valid():
            cf.save()
            return redirect(to=reverse("main:index"))
    return render(request, 'user/center.html', context={"cf": cf})
